package com.jing.myservice.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.jing.myservice.IMyAidlInterface;

public class MyBinderService extends Service {
    private static final String TAG = "MyComplexService";
    private boolean isRunning = false;
    private int count = 0;

    // 实现 AIDL 接口的 Stub 类
    private final IMyAidlInterface.Stub mBinder = new IMyAidlInterface.Stub() {
        @Override
        public void startTask() throws RemoteException {
            startBackgroundTask();
        }

        @Override
        public void stopTask() throws RemoteException {
            stopBackgroundTask();
            stopSelf();
        }
        @Override
        public int getCount() throws RemoteException {
            return count;
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "Service created");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "Service destroyed");
        stopBackgroundTask();
    }

    private void startBackgroundTask() {
        if (isRunning) return;
        isRunning = true;

        new Thread(() -> {
            while (isRunning) {
                try {
                    Thread.sleep(1000);
                    count++;
                    Log.d(TAG, "count-->>"+count);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void stopBackgroundTask() {
        isRunning = false;
    }
}